package withdraw

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/query"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

func IsPage(ret *rpc.Pagination) bool {
	if ret != nil {
		if ret.GetPage() <= 0 {
			ret.Page = 1
		}
		if ret.GetPageSize() <= 0 {
			ret.PageSize = 10
		}
		return true
	}
	return false
}

type UserAuthModel struct {
	ctx context.Context
	db  *gorm.DB
	logx.Logger
}

func (model *UserAuthModel) getDb() *gorm.DB {
	if model.db != nil {
		return model.db
	}

	return svc.Db
}
func NewUserAuthModel(ctx context.Context, db *gorm.DB) *UserAuthModel {
	return &UserAuthModel{
		ctx:    ctx,
		db:     db,
		Logger: logx.WithContext(ctx),
	}
}
func (l *UserAuthModel) UserAuthModelAdd(in *rpc.UserAuth) (*rpc.UserAuth, error) {
	g := query.Use(l.getDb()).UserAuth
	g.Where(g.ID.Eq(in.ID)).Create(in)
	return in, nil
}
func (l *UserAuthModel) UserAuthModelUpdate(in *rpc.UserAuth) (*rpc.UserAuth, error) {
	g := query.Use(l.getDb()).UserAuth
	g.Where(g.ID.Eq(in.ID)).Updates(in)
	return in, nil
}
func (l *UserAuthModel) UserAuthModelDel(id int64) error {
	g := query.Use(l.getDb()).UserAuth
	_, err := g.Where(g.ID.Eq(id)).Delete()
	return err
}
func (l *UserAuthModel) UserAuthModelList(req *rpc.UserAuthListPageReq) (ret *rpc.UserAuthListPageRes, err error) {
	ret = &rpc.UserAuthListPageRes{
		Page: req.GetPage(),
	}
	g := query.Use(l.getDb()).UserAuth
	h := g.Where()
	in := req.GetData()
	if in.ID != 0 {
		h = h.Where(g.ID.Eq(in.ID))
	}
	if in.UserId != 0 {
		h = h.Where(g.UserId.Eq(in.UserId))
	}
	if in.UserName != "" {
		h = h.Where(g.UserName.Eq(in.UserName))
	}
	if in.UserAuth != "" {
		h = h.Where(g.UserAuth.Eq(in.UserAuth))
	}
	if IsPage(ret.GetPage()) {
		if req.GetPage().GetSortOrder() == "asc" {
			h = h.Order(g.CreatedAt.Asc())
		} else {
			h = h.Order(g.CreatedAt.Desc())
		}
		ret.Page.Total, err = h.Count()
		if err != nil {
			return nil, err
		}
		ret.Data, _, err = h.FindByPage(int((ret.GetPage().GetPage()-1)*req.GetPage().GetPageSize()), int(req.GetPage().GetPageSize()))
	} else {
		ret.Data, err = h.Order(g.CreatedAt.Desc()).Find()

	}
	if err != nil {
		return nil, xerrors.ErrNoRows
	}
	return ret, nil
}
